/**
 * 登陆中间件
 */
const User = require("../model/user");
const verify = require('../config/verify')
const login = (req, res, next) => {
  let { username, password } = req.body;
  User.login(username, password)
    .then((result) => {
      if (!result[0])return next()
      verify.setToKen(result[0].id).then(token => {
        req.session.user = result;
        req.user = result;
        req.token = token;
        next();
      })
    })
    .catch((err) => {
      next(err);
    });
};
const info = (req, res, next) => {
  console.log(req.query);
}
// 获取用户列表
const UserList = (req, res, next) => {
  User.UserList()
    .then((res) => {
      let total = Math.ceil(res.length / 10);
      req.total = total
      req.userList = res;
      next();
    })
    .catch((err) => {
      next(err);
    });
};
// 用户删除
const delUser = (req, res, next) => {
  let { id } = req.body
  if (!id) {
    next();
    return;
  }
  User.delUser(id)
    .then((res) => {
      req.affectedRows = res;
      next();
    })
    .catch((err) => {
      next(err);
    });
};
// 用户添加
const userAdd = (req, res, next) => {
  let userList = req.body;
  User.userAdd(userList)
    .then((res) => {
      req.insertId = res;
      next();
    })
    .catch((err) => {
      next(err);
    });
};
// 用户编辑
const editUser = (req, res, next) => {
  // console.log(req.query);
  User.editUser(req.body)
    .then((resolve) => {
      req.affectedRows = resolve;
      next();
    })
    .catch((err) => {
      next(err);
    });
};
module.exports = { login, UserList, delUser, userAdd, editUser, info };
